package com.learn.demo.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Freemarker渲染邮件
 *
 * @author banjiawei
 * @date 2021/06/23
 */
@RestController
public class ThymeleafMailController {
    @Autowired
    TemplateEngine templateEngine;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    @RequestMapping("/tf/sendThymeleafMail")
    public void sendThymeleafMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true, "utf-8");
        helper.setSubject("这是一封thymeleaf渲染的测试邮件");
        helper.setFrom(username);
        List<String> stringList = Arrays.asList("2221512643@qq.com", "331939299@qq.com");
        String[] strings = new String[stringList.size()];
        stringList.toArray(strings);
        helper.setTo(strings);
//        helper.setCc("37xxxxx37@qq.com");
//        helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());
        // 这里引入的是Template的Context
        Context context = new Context();
        // 设置模板中的变量
        context.setVariable("name", "百姓关注");
        context.setVariable("age","19");
        context.setVariable("phone", "13984842424");
        // 第一个参数为模板的名称
        String process = templateEngine.process("mail.html", context);
        // 第二个参数true表示这是一个html文本
        helper.setText(process,true);
        javaMailSender.send(mimeMessage);
    }
}
